<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="选择学生" prop="student">
      <el-select v-model="form.student" placeholder="请选择学生">
        <el-option
          v-for="student in students"
          :key="student.stuId"
          :label="student.name"
          :value="student.stuId"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="干部名称" prop="position">
      <el-input v-model="form.position" placeholder="请输入干部名称"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const students = ref([]);

const form = ref({
  student: '',
  position: '',
});

// 获取成员列表
const fetchMembers = async () => {
  const orgId = localStorage.getItem('loginId');
  try {
    const res = await axios.get(`http://localhost:8080/orgs/${orgId}/members`);
    if (res.data && res.data.code === 200) {
      // res.data.data 是 List<Student>
      students.value = res.data.data || [];
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取成员失败');
    }
  } catch (error) {
    ElMessage.error('获取成员失败');
  }
};

onMounted(fetchMembers);

const submitForm = async () => {
  if (!form.value.student) {
    ElMessage.error('请选择学生');
    return;
  }
  if (!form.value.position) {
    ElMessage.error('请输入干部名称');
    return;
  }
  const orgId = localStorage.getItem('loginId');
  try {
    const res = await axios.post(
      `http://localhost:8080/orgs/${form.value.student}/${form.value.position}/addMembers`,
      {
        "id": Number(orgId)
      }
    );
    if (res.data && res.data.code === 200) {
      ElMessage.success(`已成功将学生设置为${form.value.position}`);
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '设置失败');
    }
  } catch (error) {
    ElMessage.error('设置失败');
  }
};

const resetForm = () => {
  form.value.student = '';
  form.value.position = '';
};
</script>